package com.sp.homework;

import java.util.Scanner;

/**
 * 1. 在main方法中启动两个线程
 * 2. 第1个线程循环随机打印100以内的整数
 * 3. 直到第2个线程从键盘读取了 "Q" 指令
 */
public class Homework01 {
    public static void main(String[] args) {
        A a = new A();
        B b = new B(a);
        Thread threadA = new Thread(a);
        Thread threadB = new Thread(b);
        threadA.start();
        threadB.start();
    }
}

class A implements Runnable {

    private boolean loop = true;
    @Override
    public void run() {
        while (loop) {
            System.out.println(Thread.currentThread().getName() + " " + (int)(Math.random() * 100 + 1) );
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("a线程退出");
    }

    public void setLoop (boolean loop) {
        this.loop = loop;
    }
}

class B implements Runnable {
    private A a;
    private Scanner scanner = new Scanner(System.in);

    public B(A a) {//构造器中传入A类对象
        this.a = a;
    }

    @Override
    public void run() {
        while (true){
            if (scanner.hasNext()){
                char key = scanner.next().toUpperCase().charAt(0);
                if (key == 'Q') {
                    a.setLoop(false);
                    System.out.println("b线程退出.");
                    break;
                }
            }
        }
    }
}